Ext.define('TS.controller.Inventory', {
    extend: 'Ext.app.Controller',
    models: ['inv.InventoryModel','inv.ProductBatchNoModel','inv.ProductContactModel'],
    stores: [
        'inv.InventoryStore','inv.ProductBatchNoStore','inv.ProductContactStore',
        'PeriodStore'
    ],
    views: [
        'inv.InventoryList','inv.InventoryInfo','inv.ProductBatchNoList','inv.ProductBatchNoDialog',
        'inv.ProductBatchNoEditer','inv.InventoryAddProduct','inv.ProductContactList','inv.ProductContactQuery'
    ],
    init: function() {
        this.control({ 
        	'inventorylist':{
        		itemdblclick: this.itemShow
        	},
        	'inventoryinfo inventorylist button[action=addnew]':{
        		click: this.addNewProduct
        	},
        	'inventoryinfo inventorylist button[action=lock]':{
        		click: this.updateInvState
        	},
        	'inventoryinfo inventorylist button[action=delzero]':{
        		click: this.delInvZero
        	},
        	'inventoryinfo inventorylist button[action=unlock]':{
        		click: this.updateInvState
        	},
        	'inventoryinfo inventorylist button[action=exportxls]':{
        		click: this.exportXLS
        	},
        	'inventoryinfo inventorylist button[action=ref]':{
        		click: this.refInventory
        	},
	        'inventoryinfo prodclassifytree':{
	        	itemclick:this.loadInvByClassid
	        },
	        'inventoryinfo invaddslist':{
	        	itemclick:this.loadInvByInvAdd
	        },
	        'inventoryinfo prodclassifytree button[action=all]':{
	        	click:this.loadInvAll
	        },
	        'inventoryinfo inventorylist triggerfield':{
	        	specialkey: this.searchProduct
	        },
	        'productbatchnolist button[action=add]':{
	        	click:this.addProductBatchNo
	        },
	        'productbatchnolist button[action=upd]':{
	        	click:this.btnEditProductBatchNo
	        },
	        'productbatchnolist button[action=del]':{
	        	click:this.delProductBatchNo
	        },
	        'prodbatchnoediter button[action=save]':{
	        	click:this.updateProductBatchNo
	        },
	        'inventoryaddproduct button[action=save]':{
	        	click:this.initNewProductInv
	        },
	        'productcontactquery triggerfield[name=productCode]':{
	        	specialkey: this.searchContactProduct
	        },
	        'productcontactquery triggerfield[name=batchNo]':{
	        	specialkey: this.searchContactProductBatchNo
	        },
	        'inventoryaddproduct triggerfield[name=productCode]':{
	        	specialkey: this.searchAddInvProduct
	        },
	        'productcontactquery button[action=searchdate]':{
	        	click:this.searchContactByDate
	        },
	        'productcontactquery button[action=searchperiod]':{
	        	click:this.searchContactByPeriod
	        },
	        'inventoryaddproduct triggerfield[name=batchNo]':{
	        	specialkey:this.searchAddInvBatchNO
	        }
        });
    },
    exportXLS:function(btn){
		var tree=btn.ownerCt.ownerCt.ownerCt.ownerCt.ownerCt.down('prodclassifytree');
    	var nodes=tree.getSelectionModel().getSelection();
    	var classifyId=1;
    	if(nodes.length == 1){
    		classifyId=nodes[0].get('classifyId');
    	}
    	//location.href=("inv/getXLS.do");
    	window.open("inv/getXLS.do?classifyId="+classifyId);
    },
    refInventory:function(btn){
    	var grid=btn.ownerCt.ownerCt;
    	grid.store.reload();
    },
    itemShow:function(grid,record){
    	console.log(record);
    },
    loadInvByInvAdd:function(grid,record){
    	var invid=record.get('id');
    	var invlist=grid.ownerCt.ownerCt.ownerCt.down('inventorylist');
    	invlist.store.on("beforeload",function(){
	        Ext.apply(invlist.store.proxy,{url:'inv/searchByInvAdd.do'});
	        Ext.apply(invlist.store.proxy.extraParams, {invAddId:invid});
	    });
     	invlist.store.loadPage(1,{
     		url:'inv/searchByInvAdd.do',
     		params:{invAddId:invid},
    		callback:function(records, operation, success){
		    	//
    		},
	   		scope: this
     	});
    },
    addNewProduct:function(btn){
    	/*var view=Ext.create('TS.view.inv.ProductBatchNoDialog');
    	view.on({
		    selected: function(records){
		    	alert(records[0].get('productId'))
		    	view.close();
		    },
		    scope: this
		});
    	view.show();*/
    	var grid=btn.ownerCt.ownerCt;
    	var rp=Ext.create('TS.model.base.ProductModel');
    	var view = Ext.widget('inventoryaddproduct');
		view.setParentCt(grid);
    	view.down('form').loadRecord(rp);
    	view.show();
    },
    updateInvState:function(btn){
    	var text=btn.text;
    	var state=0;
    	if(text=='禁用')
    		state=1;
    	var grid=btn.ownerCt.ownerCt;
    	var data=grid.getSelectionModel().getSelection();
    	if(data.length == 1){
    		if(data[0].get('state')==state) return;
	    	Ext.Ajax.request({
					    url:'inv/invupdstate.do',
					    method : 'POST',
					    timeout :3000,
					    params:{invId:data[0].get('id'),state:state},
					    success:function(response){		
					    	var rs=Ext.decode(response.responseText);
					    	if(rs.success==true){
					    		data[0].set('state',state);
					    		if(state==1){
					    			data[0].set('usableQty',0);
					    		}else{
					    			var qty=data[0].get('beginQty')+data[0].get('inQty')-data[0].get('outQty')+data[0].get('waitInQty')-data[0].get('waitOutQty');
					    			data[0].set('usableQty',qty);
					    		}
					    		grid.store.commitChanges();
					    	}
					    	showExtReturnMsg(response);
					    }
		    });
    	}else{
    		Ext.Msg.alert('提示','请您选择要'+text+"的行");
    	}
    },
    loadInvAll:function(btn){
    	var tree=btn.ownerCt.ownerCt;
    	var invlist=tree.ownerCt.ownerCt.ownerCt.down('inventorylist');
    	invlist.store.on("beforeload",function(){
	        Ext.apply(invlist.store.proxy,{url:'inv/searchInvByClassify.do'});
	        Ext.apply(invlist.store.proxy.extraParams, {classifyId:1});
	    });
     	invlist.store.loadPage(1,{
     		url:'inv/searchInvByClassify.do',
     		params:{classifyId:1},
    		callback:function(records, operation, success){
		    	//
    		},
	   		scope: this
     	});
    },
    loadInvByClassid:function(tree,record){
    	var classifyId=record.get('id');
     	var invlist=tree.ownerCt.ownerCt.ownerCt.down('inventorylist');
     	invlist.store.on("beforeload",function(store){
	        Ext.apply(store.proxy,{url:'inv/searchInvByClassify.do'});
	        Ext.apply(store.proxy.extraParams, {classifyId:classifyId});
	    });
     	invlist.store.loadPage(1,{
     		url:'inv/searchInvByClassify.do',
     		params:{classifyId:classifyId},
    		callback:function(records, operation, success){
		    	//
    		},
	   		scope: this
     	});
    },
    searchProduct:function(field,e){
    	if(e.keyCode==e.ENTER){
	    	var val=field.value;
	    	var panel=field.ownerCt.ownerCt;
	    	panel.store.on("beforeload",function(store){
		        Ext.apply(store.proxy,{url:'inv/searchInventory.do'});
		        Ext.apply(store.proxy.extraParams, {val:val});
		    });
	    	panel.store.loadPage(1,{
	    		url:'inv/searchInventory.do',
	     		params:{val:val},
	    		callback:function(records, operation, success){
			    	//
	    		},
		   		scope: this
	    	})
    	}
    },
    addProductBatchNo:function(btn){
    	var grid=btn.ownerCt.ownerCt;
    	var dialog=grid.ownerCt.ownerCt;
    	var pid=dialog.getProdId();
    	var pr=dialog.down('form').getRecord();
    	
    	if(Ext.isEmpty(pid)){
    		Ext.Msg.alert("提示","请先查询选择要添加的商品");
    	}else{
    		if(pr && !pr.get('batchMgr')){
	    		Ext.Msg.alert("提示","非批号管理商品不能添加批号");
	    		return ;
	    	}
    		var record=Ext.create('TS.model.inv.ProductBatchNoModel');
    		record.set('productId',pid);
    		var view = Ext.widget('prodbatchnoediter');
			view.setParentCt(grid);
        	view.down('form').loadRecord(record);
        	view.show();
    	}
    },
    btnEditProductBatchNo:function(btn){
    	var grid=btn.ownerCt.ownerCt;
    	var data=grid.getSelectionModel().getSelection();
    	if(data.length == 0){
			Ext.Msg.alert("提示","请选择一条要修改的数据");
		}else{
			var record=data[0];
			var view = Ext.widget('prodbatchnoediter');
			view.setParentCt(grid);
        	view.down('form').loadRecord(record);
        	view.show();
		}
    },
    updateProductBatchNo:function(btn){
    	var win    = btn.up('window'),
    	grid  =win.getParentCt(),
        form   = win.down('form');
        //非空检查
        if(!form.isValid())
        {
        	return;
        }
        var record = form.getRecord(),
        values = form.getValues();
        record.set(values);
        win.close();
        Ext.Ajax.request({
				    url:'inv/updprodbatchno.do',
				    method : 'POST',
				    timeout :3000,
				    jsonData:record.data,
				    success:function(response){		
				    	var data=Ext.decode(response.responseText);
				    	if(data.success==true){
				    		//grid.store.commitChanges();
				    		grid.store.reload();
				    	}else{
				    		grid.store.rejectChanges();
				    	}
				    	showExtReturnMsg(response);
				    }
	    });
    },
    delProductBatchNo:function(btn){
    	
    },
    initNewProductInv:function(btn){
    	var win    = btn.up('window'),
    	grid  =win.getParentCt(),
        form   = win.down('form');
        //非空检查
        if(!form.isValid())
        {
        	return;
        }
        var record = form.getRecord(),
        values = form.getValues();
        record.set(values);
        var bform=win.items.items[1];
        var bvalues=bform.getValues();
    	if(Ext.isEmpty(bvalues.id)){
    		Ext.Msg.alert('提示','请选择商品批号,如没有请自行添加')
    		return ;
    	}
        win.close();
        Ext.Ajax.request({
				    url:'inv/invaddnew.do',
				    method : 'POST',
				    timeout :5000,
				    params:{prodId:record.get('productId'),batchNoId:bvalues.id,invAddId:bvalues.invAddId},
				    success:function(response){		
				    	var data=Ext.decode(response.responseText);
				    	if(data.success==true){
				    		//grid.store.commitChanges();
				    		grid.store.loadData(data.o,true);
				    		grid.store.commitChanges();
				    	}else{
				    		grid.store.rejectChanges();
				    	}
				    	showExtReturnMsg(response);
				    }
	    });
        
    },
    delInvZero:function(btn){
    	var grid=btn.ownerCt.ownerCt;
    	var data=grid.getSelectionModel().getSelection();
    	if(data.length == 0){
			Ext.Msg.alert("提示","请选择需删除的数据");
		}else{
			var record=data[0];
			if(record.get('beginQty')!=0 || record.get('beginAmt')!=0 || record.get('inQty')!=0 || record.get('inAmt')!=0 || record.get('outQty')!=0 || record.get('outAmt')!=0){
				Ext.Msg.show({title:'删除提示',
			       msg: '删除库存商品，期初、出入库数量与金额都必须为零',
			       buttons: Ext.Msg.OK,
			       icon: Ext.Msg.WARNING});
				return;
			}
			Ext.Msg.confirm('删除商品','真的要删除选择的商品吗?',function(b){
				if(b=='yes'){
					Ext.Ajax.request({
					    url:'inv/delInvZero.do',
					    method : 'POST',
					    timeout :3000,
					    params:{invId:record.get('id')},
					    success:function(response){		
					    	var data=Ext.decode(response.responseText);
					    	if(data.success==true){
					    		grid.store.remove(record);
					    	}
					    	showExtReturnMsg(response);
					    }
			    	});
				}
			});
		}
    },
    searchAddInvProduct:function(field,e){
		if(e.keyCode==e.ENTER){
			var txt=field.value;									//Ext.Msg.alert('提示',"field是否为空?"+Ext.isEmpty(field)+"<br>Ext.isEmpty('',true)的值:"+Ext.isEmpty(txt,true)+"<br>Ext.isEmpty('',false)的值"+Ext.isEmpty(txt,false));
			if(!Ext.isEmpty(txt)){
				var view=Ext.create('TS.view.base.ProductSearchDialog');
		    	view.setVal(txt);
		    	view.on({
				    selected: function(records){
				    	if(records){
				    		if(records.length>0){
				    			var form=field.up('form');
				    			form.loadRecord(records[0]);
				    		}
				    	}
				    	view.close();
				    },
				    scope: this
				});
		    	view.show();
			}
		}
    },
    searchContactProduct:function(field,e){
		if(e.keyCode==e.ENTER){
			var txt=field.value;
			if(!Ext.isEmpty(txt)){
				var view=Ext.create('TS.view.base.ProductSearchDialog');
				view.setVal(txt);
				view.on({
			    selected: function(records){
			    	if(records){
			    		if(records.length>0){
			    				var form=field.up('form');
			    				form.loadRecord(records[0]);
			    				form.items.items[1].down('hiddenfield').setValue(null);
			    				form.items.items[1].down('triggerfield').setValue(null);
					    	}
					    }
					    view.close();
				    },
				    scope: this
				});
		    	view.show();
			}
		}
    },
    searchAddInvBatchNO:function(field,e){
       if(e.keyCode==e.ENTER){									
			var view=Ext.create('TS.view.inv.ProductBatchNoDialog');
			var form=field.up('window').down('form');
			var prod=form.getRecord()
			if(Ext.isEmpty(prod)){
				Ext.Msg.alert('提示','请先选择商品!')
				return;
			}
			var pid=prod.get('productId');
			if(Ext.isEmpty(pid)){
				Ext.Msg.alert('提示','请先选择商品!')
				return;
			}
	    	view.setProdId(pid);
	    	view.setPrecord(prod);
	    	view.on({
			    selected: function(records){
			    	if(records){
			    		if(records.length>0){
			    			if(records[0].get('productId')!=pid){
			    				Ext.Msg.alert('提示','选择批号商品与当前商品不同,请重新选择!')
			    				return ;
			    			}
			    			field.up('form').loadRecord(records[0]);
			    		}
			    	}
			    	view.close();
			    },
			    scope: this
			});
	    	view.show();
		}
    },
    searchContactProductBatchNo:function(field,e){
		if(e.keyCode==e.ENTER){									
			var view=Ext.create('TS.view.inv.ProductBatchNoDialog');
			var prod=field.up('form').getRecord();
			if(Ext.isEmpty(prod)){
				Ext.Msg.alert('提示','请先选择商品!')
				return;
			}
			var pid=prod.get('productId');
			if(Ext.isEmpty(pid)){
				Ext.Msg.alert('提示','请先选择商品!')
				return;
			}
	    	view.setProdId(pid);
	    	view.setPrecord(prod);
	    	view.on({
			    selected: function(records){
			    	if(records){
			    		if(records.length>0){
			    			if(records[0].get('productId')!=pid){
			    				Ext.Msg.alert('提示','选择批号商品与当前商品不同,请重新选择!')
			    				return ;
			    			}
			    			var form=field.up('form');
			    			form.loadRecord(records[0]);
			    		}
			    	}
			    	view.close();
			    },
			    scope: this
			});
	    	view.show();
		}    	
    },
    searchContactByDate:function(btn){
    	var grid=btn.up('form').up('panel').down('grid');
    	var form =btn.up('form');
    	if(!form.isValid())
        {
        	return;
        }
    	var v=form.getValues();
    	if(!v.id || !v.productId){
			Ext.Msg.show({title:'查询提示',
		       msg: '请选择商品和批号后再查询',
		       buttons: Ext.Msg.OK,
		       icon: Ext.Msg.WARNING});
			return;
		}
    	grid.store.load({
    		url:'inv/invflowquerybydate.do',
     		params:{invAddId:loginUser.currentInvAdd,productId:v.productId,batchNoId:v.id,begDate:v.beginDate,endDate:v.endDate},
    		callback:function(records, operation, success){
		    	if(success==false){
		    		Ext.Msg.show({title:'提示',
				       msg: this.proxy.reader.jsonData.msg,
				       buttons: Ext.Msg.OK,
				       icon: Ext.Msg.WARNING
				    });
		    	}
    		},
	   		scope: this
    	})
    },
    searchContactByPeriod:function(btn){
    	var grid=btn.up('form').up('panel').down('grid');
    	var form =btn.up('form');
    	if(!form.isValid())
        {
        	return;
        }
    	var v=form.getValues();
    	var begPeriod=v.begYear+'.'+Ext.String.leftPad(v.begMonth,2, '0');
    	var endPeriod=v.endYear+'.'+Ext.String.leftPad(v.endMonth,2, '0');
    	grid.store.load({
     		params:{invAddId:v.invadd,productId:v.productId,batchNoId:v.id,begPeriod:begPeriod,endPeriod:endPeriod},
    		callback:function(records, operation, success){
		    	if(success==false){
		    		Ext.Msg.show({title:'提示',
				       msg: this.proxy.reader.jsonData.msg,
				       buttons: Ext.Msg.OK,
				       icon: Ext.Msg.WARNING
				    });
		    	} 
    		}
    	})
    }
});